package com.zygk.library.base;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Window;
import butterknife.ButterKnife;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.zygk.library.util.ActivityCollector;
import com.zygk.library.util.PreferencesHelper;
import com.zygk.library.util.GlideImageLoader;
import com.zygk.library.util.ImageManager;
import com.zygk.library.util.StringUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.library.util.imagePicker.ImagePickerAdapter;
import com.zygk.library.view.LibraryCommonDialog;
import com.zygk.library.view.LoadingDialog;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public abstract class BaseActivity extends AppCompatActivity {
  public static final int IMAGE_ITEM_ADD = -1;
  public static final int REQUEST_CODE_SELECT = 9000;
  public static final int REQUEST_CODE_PREVIEW = 9001;
  public static final int REQUEST_CODE_CAMERA = 9002;

  public LoadingDialog loadingDialog;
  private InternalReceiver internalReceiver;
  public ImageManager imageManager;
  public Context mContext;
  public FragmentActivity mActivity;
  public PreferencesHelper preferencesHelper;
  public LayoutInflater layoutInflater;

  public ImagePicker imagePicker;
  private int maxCount = 1;
  private ArrayList<ImageItem> selectImageList = null;

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView();
    ButterKnife.bind(this);
    loadingDialog = new LoadingDialog(this);
    loadingDialog.setMessageText("加载中...");

    imageManager = new ImageManager(this);
    imagePicker = ImagePicker.getInstance();
    imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
    mContext = this;
    mActivity = this;
    preferencesHelper = new PreferencesHelper(mContext);
    layoutInflater = getLayoutInflater();

    init();
    // 每创建一个活动，就加入到活动管理器中
    ActivityCollector.addActivity(this);
  }

  /**
   * 初始化layout
   */
  public abstract void setContentView();

  /**
   * 初始化数据和空间
   */
  public abstract void init();
  //private void initData(){}
  //private void initView(){}
  //private void initListener(){}

  public void showPd() {
    try {
      if (loadingDialog != null && !loadingDialog.isShowing()) {
        loadingDialog.show();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  protected void showNoCancelPd() {
    if (loadingDialog != null && !loadingDialog.isShowing()) {
      loadingDialog.setCanceledOnTouchOutside(false);
      loadingDialog.setCancelable(false);
      loadingDialog.show();
    }
  }

  public void dismissPd() {
    try {
      if (loadingDialog != null && loadingDialog.isShowing()) {
        loadingDialog.dismiss();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  protected final void registerReceiver(String[] actionArray) {
    if (actionArray == null) {
      return;
    }
    IntentFilter intentfilter = new IntentFilter();
    for (String action : actionArray) {
      intentfilter.addAction(action);
    }
    if (internalReceiver == null) {
      internalReceiver = new InternalReceiver();
    }
    registerReceiver(internalReceiver, intentfilter);
  }

  // Internal class.
  private class InternalReceiver extends BroadcastReceiver {

    @Override public void onReceive(Context context, Intent intent) {
      if (intent == null || intent.getAction() == null) {
        return;
      }
      handleReceiver(context, intent);
    }
  }

  /**
   * 如果子界面需要拦截处理注册的广播 需要实现该方法
   */
  protected void handleReceiver(Context context, Intent intent) {
    // 广播处理
    if (intent == null) {
      return;
    }
  }

  @Override protected void onDestroy() {
    try {
      if (internalReceiver != null) {
        unregisterReceiver(internalReceiver);
      }
    } catch (Exception e) {
    }

    // 每销毁一个活动，就从活动管理器中移除
    ActivityCollector.removeActivity(this);
    super.onDestroy();
  }

  /**
   * 初始化单选拍照
   */
  protected void initImagePickerSingle(boolean crop) {
    imagePicker.setMultiMode(false);                      // 单选
    imagePicker.setShowCamera(false);                      //显示拍照按钮
    imagePicker.setCrop(crop);                           //允许裁剪（单选才有效）
    imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
    imagePicker.setSelectLimit(1);                        //选中数量限制
    imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
    imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
    imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
    imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
    imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
  }

  /**
   * 初始化多选拍照
   */
  protected void initImagePickerMulti(int maxCount) {
    imagePicker.setMultiMode(true);                      // 单选
    imagePicker.setShowCamera(false);                      //显示拍照按钮
    imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
    imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
    imagePicker.setSelectLimit(maxCount);              //选中数量限制
    imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
    imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
    imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
    imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
    imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
  }

  /**
   * 单张（拍照or相册）
   */
  protected void picOne() {
    this.maxCount = 1;
    this.selectImageList = null;

    LibraryCommonDialog.addPhotoDialog(mContext, new LibraryCommonDialog.AddPhotoCallback() {
      @Override public void onTakePic() {
        if (AndPermission.hasPermission(mContext, Manifest.permission.CAMERA)) {
          takePic(maxCount, selectImageList);
        } else {
          requestCameraPermission();
        }
      }

      @Override public void onChoosePoc() {
        choosePic(1, null);
      }
    });
  }

  /**
   * 多张（拍照or相册）
   */
  protected void picMulti(int maxCount2, ArrayList<ImageItem> selectImageList2) {
    this.maxCount = maxCount2;
    this.selectImageList = selectImageList2;

    LibraryCommonDialog.addPhotoDialog(mContext, new LibraryCommonDialog.AddPhotoCallback() {
      @Override public void onTakePic() {
        if (AndPermission.hasPermission(mContext, Manifest.permission.CAMERA)) {
          takePic(maxCount, selectImageList);
        } else {
          requestCameraPermission();
        }
      }

      @Override public void onChoosePoc() {
        choosePic(maxCount, selectImageList);
      }
    });
  }

  /**
   * 拍照
   */
  protected void takePic(int maxCount, final ArrayList<ImageItem> selectImageList) {
    if (AndPermission.hasPermission(mContext, Manifest.permission.CAMERA)) {
      if (maxCount > 1) imagePicker.setSelectLimit(maxCount - selectImageList.size());
      Intent intent = new Intent(mContext, ImageGridActivity.class);
      intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
      startActivityForResult(intent, REQUEST_CODE_SELECT);
    } else {
      requestCameraPermission();
    }
  }

  /**
   * 相册选择
   */
  protected void choosePic(int maxCount, final ArrayList<ImageItem> selectImageList) {
    if (maxCount > 1) imagePicker.setSelectLimit(maxCount - selectImageList.size());

    //打开选择,本次允许选择的数量
    Intent intent = new Intent(mContext, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
    //            intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES, images);
    startActivityForResult(intent, REQUEST_CODE_SELECT);
  }

  /**
   * 预览图片
   */
  protected void previewPic(ImagePickerAdapter imagePickerAdapter, int position) {
    //打开预览
    Intent intentPreview = new Intent(mActivity, ImagePreviewDelActivity.class);
    intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS,
        (ArrayList<ImageItem>) imagePickerAdapter.getImages());
    intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
    intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
    startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
  }

  private void requestCameraPermission() {
    AndPermission.with(this)
        .requestCode(REQUEST_CODE_CAMERA)
        .permission(Manifest.permission.CAMERA)
        .callback(this)
        .start();
  }

  @PermissionYes(REQUEST_CODE_CAMERA)
  private void getPermissionYes(List<String> grantedPermissions) {
    takePic(maxCount, selectImageList);
  }

  @PermissionNo(REQUEST_CODE_CAMERA) private void getPermissionNo(List<String> deniedPermissions) {
    ToastUtil.showMessage(mContext, "无摄像头权限, 请前往设置中心开启摄像头权限");
  }

  protected void compareGPSopen() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return;
    LocationManager mLocationManager =
        (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
      LibraryCommonDialog.showYesOrNoDialog(mContext, "请打开GPS服务", "您未开启GPS服务，为了app的正常使用，请前往设置中心开启！", null, "设置", new LibraryCommonDialog.OnYesCallback() {
        @Override
        public void onYesClick() {
          // 转到手机设置界面，用户设置GPS
          Intent intent = new Intent(
                  Settings.ACTION_LOCATION_SOURCE_SETTINGS);
          startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
        }
      }, null);
    }
  }

  /**
   * get App versionCode
   */
  public int getVersionCode() {
    PackageManager packageManager = mContext.getPackageManager();
    PackageInfo packageInfo;
    int versionCode = -1;
    try {
      packageInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
      versionCode = packageInfo.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }
    return versionCode;
  }

  /**
   * get App versionName
   */
  public String getVersionName() {
    PackageManager packageManager = mContext.getPackageManager();
    PackageInfo packageInfo;
    String versionName = "";
    try {
      packageInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
      versionName = packageInfo.versionName;
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }
    return versionName;
  }

  /**
   * 清除用户信息
   */
  public void clearUserInfo(boolean clearLoginName){
    if(clearLoginName){
      PreferencesHelper.setSettingString(PreferencesHelper.User.Key.USER_NAME, "");
    }
    PreferencesHelper.setSettingString(PreferencesHelper.User.Key.USER_PWD, "");
    PreferencesHelper.setSettingBoolean(PreferencesHelper.User.Key.USER_PWD_REMEMBER, false);

    PreferencesHelper.userManager().saveUserInfo(null);
    PreferencesHelper.userManager().saveUserID("");
    PreferencesHelper.userManager().saveToken("");
  }
}
